package com.example.session;

import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import com.example.config.MqttPersistenceConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class SessionManager {
    private final Map<String, MqttSession> sessions = new ConcurrentHashMap<>();
    private final MqttPersistenceConfig persistenceConfig;
    private final RedisTemplate<String, Object> redisTemplate;
    
    public SessionManager(MqttPersistenceConfig persistenceConfig,
                         @Autowired(required = false) RedisTemplate<String, Object> redisTemplate) {
        this.persistenceConfig = persistenceConfig;
        this.redisTemplate = redisTemplate;
    }
    
    public void addSession(String clientId, MqttSession session) {
        sessions.put(clientId, session);
        if (persistenceConfig.getRedis().isEnabled() && redisTemplate != null) {
            redisTemplate.opsForValue().set(
                "mqtt:session:" + clientId,
                session,
                persistenceConfig.getRedis().getSessionTimeout(),
                TimeUnit.SECONDS
            );
        }
    }
    
    public MqttSession getSession(String clientId) {
        return sessions.get(clientId);
    }
    
    public void removeSession(String clientId) {
        sessions.remove(clientId);
        if (persistenceConfig.getRedis().isEnabled() && redisTemplate != null) {
            redisTemplate.delete("mqtt:session:" + clientId);
        }
    }
} 